require "import"
import "android.content.Intent"
import "android.provider.Settings"
import "android.content.Context"
import "android.bluetooth.BluetoothAdapter"

local intent = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
this.startActivity(intent)

task(350, function()
  local bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
  local isEnabled = bluetoothAdapter.isEnabled()
  local targets = {}

  if isEnabled then
    service.play("cancel")
    targets = {
      "#switch_widget", "#sesl_switchbar_switch", "#switch_background", 
      "com.android.settings:id/switch_widget", "android:id/checkbox", "#checkbox",
      "إيقاف", "تعطيل", "Turn off", "Off", "Désactiver", "Désactivé"
    }
  else
    service.playSoundTick()
    targets = {
      "#switch_widget", "#sesl_switchbar_switch", "#switch_background", 
      "com.android.settings:id/switch_widget", "android:id/checkbox", "#checkbox",
      "تشغيل", "تفعيل", "Turn on", "On", "Activation", "Activé"
    }
  end

  if service.click(targets) or service.click("%Bluetooth$200") then
    task(400, function()
      local homeIntent = Intent(Intent.ACTION_MAIN)
      homeIntent.addCategory(Intent.CATEGORY_HOME)
      homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
      this.startActivity(homeIntent)
    end)
    return true
  end
end)
